<template>
  <div class="back-editor">
    <div class="editorTitle" v-if="editId">
      <el-dropdown
        trigger="click"
        @command="addFb"
        @visible-change="changeDown"
        v-if="dataObj.level == 2"
        style="position: absolute; right: 24px; top: 0px"
      >
        <el-button class="ai-suggestion-btn" type="primary" plain size="mini"
          >新增副本</el-button
        >
        <el-dropdown-menu slot="dropdown" v-loading="showAddListLoding">
          <el-dropdown-item v-for="(item, i) in addList" :command="i">{{
            item.title
          }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button
        class="ai-suggestion-btn"
        type="primary"
        plain
        size="mini"
        style="position: absolute; right: 24px; top: 10px"
        v-else
        @click="addFb2"
        >新增副本</el-button
      >
    </div>
    <div class="bjBox" v-if="editId && list.length">
      <div class="left">
        <el-timeline :reverse="false">
          <el-timeline-item v-for="(activity, index) in list" :key="index">
            {{
              currentType == 1 ? activity.title : initTime(activity.updated_at)
            }}
          </el-timeline-item>
        </el-timeline>
      </div>
      <div
        class="right"
        :style="'height:' + tableHeight + 'px'"
        style="overflow-y: auto"
      >
        <div class="item" v-for="(item, i) in list">
          <div class="top">
            <div class="name">
              {{
                currentType == 1
                  ? item.title
                  : item.title + "-" + initTime(item.updated_at)
              }}
              <div v-if="item.master" class="dqbb"><i></i>当前版本</div>
            </div>
            <div class="cz">
              <el-button
                type="text"
                v-if="!item.id"
                @click="aiTool(item, 'aiContent', '内容生成')"
                ><img
                  src="@/assets/images/nrsc.png"
                  alt=""
                />内容生成</el-button
              >

              <el-button
                type="text"
                v-if="item.id && !item.isEdit"
                @click="setItem(item)"
                ><img src="@/assets/images/bjBtn.png" alt="" />编辑</el-button
              >
              <el-button
                type="text"
                v-if="item.editContent && currentType == 2 && !item.master"
                @click="setDqbb(item, true)"
                ><img
                  src="@/assets/images/fbBtn.png"
                  alt=""
                />设为当前版本</el-button
              >
              <el-button
                type="text"
                v-if="currentType == 2 && item.master"
                @click="setDqbb(item, false)"
                ><img
                  src="@/assets/images/fbBtn.png"
                  alt=""
                />设为副版本</el-button
              >
              <el-button
                type="text"
                v-if="item.id"
                @click="aiTool(item, 'regen', '重新生成')"
                ><img
                  src="@/assets/images/cxscBtn.png"
                  alt=""
                />重新生成</el-button
              >
              <el-button
                type="text"
                v-if="item.id"
                @click="aiTool(item, 'refine', '内容细化')"
                ><img
                  src="@/assets/images/nrxhBtn.png"
                  alt=""
                />内容细化</el-button
              >
              <el-button
                type="text"
                v-if="item.id"
                @click="aiTool(item, 'continue', '内容续写')"
                ><img
                  src="@/assets/images/nrxxBtn.png"
                  alt=""
                />内容续写</el-button
              >
              <el-button
                type="text"
                v-if="item.id"
                @click="aiTool(item, 'expand', '内容扩展')"
                ><img
                  src="@/assets/images/nrkzBtn.png"
                  alt=""
                />内容扩展</el-button
              >

              <el-button
                type="text"
                style="color: red"
                @click="removeBB(item)"
                v-if="item.id"
                ><img src="@/assets/images/scBtn.png" alt="" />删除</el-button
              >
            </div>
          </div>
          <div class="bottom">
            <el-input
              type="textarea"
              :rows="10"
              placeholder="请输入"
              v-model="item.editContent"
              v-if="item.isEdit"
            ></el-input>

            <div class="nr" v-html="item.content" v-else></div>
          </div>
          <div class="czBox" v-if="item.isEdit">
            <el-button @click="noSetItem(item, i)">取消</el-button>
            <el-button type="primary" @click="saveItem(item)">确定</el-button>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="noDate">
      <img src="@/assets/images/zzzw.png" alt="" />
      无选中的背景节点
    </div>

    <el-dialog :title="modelTitle" :visible.sync="modelShow" width="540" center>
      <el-form
        label-position="top"
        ref="formRef"
        class="tkBox"
        label-width="80px"
      >
        <el-form-item label="选择模型">
          <el-dropdown
            class="dropdown-wrapper"
            trigger="click"
            placement="bottom-start"
          >
            <span class="el-dropdown-link">
              {{ selectedVendor || "请选择" }}
              <i class="el-icon-arrow-down el-dropdown-link-icon"></i>
            </span>

            <el-dropdown-menu slot="dropdown" class="dropdown-wrapper-list">
              <div class="moTitle">选择厂商</div>
              <el-popover
                v-for="(models, provider) in modelList"
                placement="right"
                :value="showMx && showMxType == provider"
              >
                <div class="moTitle">选择模型</div>
                <el-radio-group
                  v-model="selectedVendor"
                  @input="showMx = false"
                  class="myradio"
                >
                  <el-radio
                    v-for="item in modelList[provider]"
                    :label="item.model_name"
                    >{{ item.model_name }}</el-radio
                  >
                </el-radio-group>
                <el-dropdown-item slot="reference" :key="provider">
                  <div
                    :class="provider == showMxType ? 'active' : ''"
                    style="
                      display: flex;
                      justify-content: space-between;
                      align-items: center;
                    "
                    @mouseover="handleMouseOver(provider)"
                    @mouseout="handleMouseOut(provider)"
                  >
                    {{ provider }} <i class="el-icon-arrow-right"></i>
                  </div>
                </el-dropdown-item>
              </el-popover>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="moText">{{ getModelDesc(selectedVendor) }}</div>
        </el-form-item>
        <el-form-item label="关联上下文" prop="type">
          <el-select
            v-model="type"
            placeholder="请选择关联类型"
            style="width: 100%"
          >
            <el-option label="默认关联" :value="1"></el-option>
            <el-option label="不关联" :value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="modelShow = false">取消</el-button>
        <el-button type="primary" @click="toolSave">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { changeRoleStatus } from "@/api/system/role";
import { versionUpdate } from "@/api/versions";
import {
  archCreate,
  archDelete,
  archEdit,
  archSetmaster,
  archSetslave,
  getArchList,
  getArchMaster,
} from "@/api/arch";
import { deleteVolume } from "@/api/volumes";
import { creteArrange, getTools } from "@/api/tk";
import { conversationBuild, conversationCreate } from "@/api/conversation";
import { conversationModels, conversationDefault } from "@/api/conversations";

export default {
  name: "BackDetail",

  props: {
    editId: {},
    // dataObj 包含 { title, content }
    dataObj: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      ai_tool_id: "",
      modelTitle: "",
      creation_id: "",
      aiItem: {},
      aiType: "",
      showMx: false,
      modelList: [],
      showMxType: "",
      selectedVendor: "", // 选择的厂商
      modelShow: false,
      type: 1,
      tableHeight: 300,
      currentType: 1,
      title: "",
      list: [],
      addList: [{ title: "加载中.." }],
      showAddListLoding: true,
    };
  },
  mounted() {
    this.creation_id = Number(this.$route.params.id);
    this.$nextTick(() => {
      this.handleResize();
    });
    this.getDefaultModel();
    window.addEventListener("resize", this.handleResize);
    // 初次载入时，将「标题 + 内容」组合到编辑器
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    //获取默认模型
    async getDefaultModel() {
      const response = await conversationDefault();
      this.selectedVendor = response.model_name;
    },
    //获取模型描述
    getModelDesc(model_name) {
      const list = Object.values(this.modelList).flat();
      const item = list.find((x) => x.model_name == model_name);
      return item ? item.billing : "";
    },
    changeDown(item) {
      if (this.showAddListLoding && item) {
        getTools({
          stage_seq: Number(this.dataObj.stage_seq),
          group_seq: Number(this.dataObj.seq),
        }).then((res) => {
          this.addList = res;
          this.showAddListLoding = false;
        });
      }
      console.log(item);
    },
    async toolSave() {
      //工具
      if (this.selectedVendor == "") {
        this.$message.error("请选择模型");
        return false;
      }
      this.loading = true;
      //内容生成
      if (this.aiType == "aiContent") {
        try {
          const response = await conversationCreate({
            pattern: this.type,
            model: this.selectedVendor,
            ai_tool_id: this.ai_tool_id,
            creation_id: this.creation_id,
          });
          this.modelShow = false;
          this.drawer = false;
          this.$emit("changeDldh", {
            type: "openNew",
            id: response.conversation_id,
            show_prompt: response.show_prompt,
          });
        } catch (error) {
          this.$message.error("创建新对话失败");
        }
      } else {
        try {
          const response = await conversationBuild({
            pattern: this.type,
            element_id: this.aiItem.id,
            build_id: this.aiType,
            model: this.selectedVendor, // 示例输入
          });
          this.modelShow = false;
          this.drawer = false;
          this.$emit("changeDldh", {
            type: "openNew2",
            id: response.conversation_id,
            show_prompt: response.show_prompt,
          });
        } catch (error) {
          this.$message.error("创建新对话失败");
        }
      }
    },
    async aiTool(item, type, title) {
      this.aiType = type;
      this.aiItem = item;
      this.modelTitle = item.title + "-" + title;
      let data = await conversationModels({});
      this.modelList = data;
      this.modelShow = true;
    },
    handleResize() {
      this.tableHeight = window.innerHeight - 150;
    },
    setItem(item) {
      item.isEdit = true;
    },
    noSetItem(item, idx) {
      if (item.id) {
        item.editContent = item.content;
        item.isEdit = false;
      } else {
        this.list.splice(idx, 1);
      }
    },
    initTime(time) {
      if (time) {
        return time.split("T")[0];
      } else {
        return "现在";
      }
    },
    addFb2() {
      this.ai_tool_id = this.dataObj.keyword;
      this.list.unshift({
        title: this.dataObj.title,
        name: this.dataObj.keyword,
        master: false,
        editContent: "",
        isEdit: true,
      });
    },
    addFb(idx) {
      var item = this.addList[idx];
      this.ai_tool_id = item.name;
      this.list.unshift({
        title: item.title,
        name: item.name,
        master: false,
        editContent: "",
        isEdit: true,
      });
    },

    getItem() {
      if (this.dataObj.level == 2) {
        getArchMaster({ subset_id: Number(this.dataObj.id) }).then((res) => {
          res.forEach((item) => {
            item.isEdit = false;
            item.editContent = item.content;
          });
          this.list = res;
          this.currentType = "1";
        });
      } else {
        getArchList({
          subset_id: Number(this.dataObj.subset_id),
          keyword: this.dataObj.keyword,
        }).then((res) => {
          res.forEach((item) => {
            item.isEdit = false;
            item.editContent = item.content;
          });
          this.list = res;
          this.currentType = "2";
        });
      }
    },
    saveItem(item) {
      if (item.id) {
        archEdit({ element_id: item.id, content: item.editContent }).then(
          (res) => {
            this.$message.success("更新成功");
            this.getItem();
          }
        );
      } else {
        var id =
          this.dataObj.level == 2 ? this.dataObj.id : this.dataObj.subset_id;
        var master = this.dataObj.level == 2 ? true : false;
        archCreate({
          subset_id: Number(id),
          keyword: item.name,
          content: item.editContent,
          master: master,
        }).then((res) => {
          this.$message.success("新增成功");
          this.getItem();
        });
      }
    },
    removeBB2(idx) {
      this.list.splice(idx, 1);
    },
    removeBB(item) {
      this.$confirm("确认删除该创作要素吗？", "提示", { type: "warning" })
        .then(() => {
          // 在treeData里把它移除
          archDelete({ element_id: item.id }).then((res) => {
            this.$message.success("删除成功");
            this.getItem();
          });
        })
        .catch(() => {});
    },
    setDqbb(item, type) {
      var that = this;
      if (type) {
        this.$modal
          .confirm("确认要设置为当前版本吗？")
          .then(function () {
            archSetmaster({ element_id: item.id }).then((res) => {
              console.log(res);
              // this.currentDataObj=res.volume
              // this.currentType='1'
            });
          })
          .then(() => {
            this.$modal.msgSuccess("设置成功");
            that.getItem();
          })
          .catch(function () {
            this.$modal.msgError("设置失败");
          });
      } else {
        this.$modal
          .confirm("确认要设置为副版本吗？")
          .then(function () {
            archSetslave({ element_id: item.id }).then((res) => {
              console.log(res);

              // this.currentDataObj=res.volume
              // this.currentType='1'
            });
          })
          .then(() => {
            this.$modal.msgSuccess("设置成功");
            that.getItem();
          })
          .catch(function () {
            this.$modal.msgError("设置失败");
          });
      }
    },
    handleAISuggestion() {
      // AI生成标题的逻辑
      // 这里需要根据你的具体需求实现
      console.log("AI生成标题功能尚未实现");
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dropdown-menu {
  width: 495px;
}

.active {
  background: rgba(242, 244, 248, 1);
}

.myradio {
  display: flex;
  flex-direction: column;

  .el-radio {
    line-height: 32px;
    margin-bottom: 10px;
  }
}

.noDate {
  text-align: center;
  padding-top: 350px;
  font-size: 14px;
  color: rgba(0, 1, 27, 0.3);

  img {
    width: 140px;
    display: block;
    margin: 0 auto;
  }
}

.dqbb {
  height: 23px;
  background: rgba(22, 93, 235, 0.1);
  border-radius: 12px 12px 12px 12px;
  font-size: 12px;
  color: #165deb;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 8px;
  float: right;
  padding: 0 9px;

  i {
    width: 4px;
    height: 4px;
    background: #165deb;
    border: 2px solid rgba(22, 93, 235, 0.2);
    border-radius: 50%;
    margin-right: 2px;
  }
}

.back-editor {
  height: 100%;
  position: relative;

  .bjBox {
    min-height: 400px;
    display: flex;
    position: absolute;
    height: 100%;
    padding-top: 66px;
    left: 0;
    width: 100%;
    top: 0;

    .left {
      width: 200px;
      border-right: 1px solid rgba(0, 0, 0, 0.08);
      padding-top: 24px;
      padding-left: 24px;

      ::v-deep .el-timeline {
        padding-left: 0;
      }
    }

    .right {
      flex: 1;
      padding: 0 24px;

      .item {
        margin-bottom: 10px;

        .top {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 64px;

          .name {
            font-size: 18px;
            color: #00011b;
          }

          .cz {
            ::v-deep .el-button + .el-button {
              margin-left: 20px;
            }

            ::v-deep .el-button--medium {
              font-size: 16px;

              span {
                display: flex;
                align-items: center;
              }
            }

            img {
              width: 16px;
              height: 16px;
              margin-right: 5px;
            }
          }
        }

        .bottom {
          .nr {
            white-space: pre-wrap;
            background: #f6f7fa;
            border-radius: 6px 6px 6px 6px;
            padding: 12px;
            font-size: 16px;
            color: #00011b;
            line-height: 24px;
          }
        }

        .czBox {
          text-align: right;
          margin-top: 12px;
        }
      }
    }
  }

  .editorTitle {
    position: absolute;
    top: 0;
    line-height: 64px;
    height: 64px;
    width: 100%;
    padding: 0 24px;
    z-index: 999;
    font-size: 18px;
    color: #000000;
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    font-weight: bold;
  }

  .ai-suggestion-btn {
    background: linear-gradient(90deg, #3c7dff 0%, #165deb 100%);
    border-radius: 6px;
    height: 32px;
    color: #fff;
  }

  .operation-box {
    position: absolute;
    line-height: 18px;
    font-size: 12px;
    font-weight: bold;
    background: #fff;
    box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.2);
    border-radius: 8px 8px 8px 8px;
    border: 1px solid rgba(0, 0, 0, 0.06);
    display: flex;
    justify-content: space-around;
    align-items: center;
    z-index: 1000;
    transition: opacity 0.3s ease;
    padding: 10px 16px;
    width: 350px;
    /* 可以根据需要调整操作框的宽高和样式 */
  }

  .operation-box div {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 12px;
    padding: 0 5px;
    color: #333;
    display: flex;
    align-items: center;
  }

  .operation-box div img {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }

  .operation-box div:hover {
    color: #165deb;
  }
}

.tkBox {
  .el-form-item__label {
    font-size: 14px;
    color: #00011b;
    line-height: 16px;
    margin-bottom: 4px;
    font-weight: normal;
    padding: 0;
  }

  .el-form-item {
    margin-bottom: 24px;
  }

  ::v-deep .el-form-item--medium .el-form-item__label {
    height: 30px;
    line-height: 30px !important;
    font-size: 13px;
    color: rgba(0, 1, 27, 0.5);
  }

  ::v-deep .el-input--medium .el-input__inner {
    height: 52px;
    line-height: 52px !important;
    font-size: 16px;
  }
}

.dropdown-wrapper {
  width: 100%;
}

.moTitle {
  font-size: 12px;
  color: rgba(0, 1, 27, 1);
  padding-left: 17px;
  line-height: 32px;
}

.el-dropdown-link {
  color: #333;
  cursor: pointer;
  padding: 7px;
  padding-left: 15px;
  border: 1px solid #c4c6cc;
  border-radius: 4px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
}

.el-dropdown-link-icon {
  margin-left: 5px;
}
</style>
